<template>
  <div class="upload-file">
    <el-upload :action="uploadFileUrl"
               :before-upload="handleBeforeUpload"
               :file-list="fileList"
               :limit="limit"
               :on-error="handleUploadError"
               :on-exceed="handleExceed"
               :on-success="handleUploadSuccess"
               :show-file-list="false"
               :headers="headers"
               :drag="isDrag"
               :data="{fileType: oFileType, parentId: oParentId}"
               :hidden="isReadonly"
               class="upload-file-uploader"
               ref="fileUpload"
               multiple>
      <!-- 上传按钮 -->
      <el-button type="primary" v-if="oType === 1">
        <svg-icon icon-class="upload" />
        <span>上传文件到此目录</span>
      </el-button>
      <el-button type="primary" link title="上传文件到此目录"  v-if="oType === 2">
        <svg-icon icon-class="upload" />
      </el-button>
      <el-icon v-if="isDrag" class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text" v-if="isDrag">
        将文件拖到此处 <em>点击上传</em>
      </div>
    </el-upload>
    <!-- 上传提示 -->
    <div class="el-upload__tip" v-if="showTip" :hidden="isReadonly">
      请上传
      <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b> </template>
      <template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b> </template>
      的文件
    </div>
  </div>
  <el-dialog v-model="attachmentVisible" title="附件预览" width="70%" top="2vh">
    <attachmentPreview v-model:attachmentId="previewAttachmentId" />
    <div style="text-align:right;">
      <el-button type="danger" @click="closeBtn">关闭</el-button>
    </div>
  </el-dialog>
</template>

<script setup>
import { getToken } from "@/config/cookie";
import {computed, getCurrentInstance, ref, watch} from "vue";
import {doDownload, doGet} from "@/config/http"
import {alertErrorMsg, alertWarningMsg, svc} from "@/config/common"
import attachmentPreview from '@/views/components/base/attachmentPreview.vue'

const props = defineProps({
  modelValue: [String, Object, Array],
  // 数量限制
  limit: {
    type: Number,
    default: 100,
  },
  // 大小限制(MB)
  fileSize: {
    type: Number,
    default: 5,
  },
  // 文件类型, 例如['png', 'jpg', 'jpeg']
  fileType: {
    type: Array,
    default: () => ["doc", "docx", "xls", "xlsx", "ppt", "pptx", "text", "txt", "pdf", "png", "jpg", "jpeg", "mp3", "mp4", "avi", "7z", "zip", "rar"],
  },
  // 是否显示提示
  isShowTip: {
    type: Boolean,
    default: true
  },
  // 是否拖拽文件上传
  isDrag: {
    type: Boolean,
    default: false
  },
  isReadonly: {
    type: Boolean,
    default: false,
  },
  oParentId: {
    type: String,
    default: null,
  },
  oType: {
    type: Number,
    default: 1,
  },
});

let attachmentVisible = ref(false)
const { proxy } = getCurrentInstance();
let previewAttachmentId = ref(null)
const emit = defineEmits(['uploadedSuccess']);
const number = ref(0);
let uploadList = [];
const uploadFileUrl = ref("/" + svc + "/api/v1/customAttachment/upload"); // 上传文件服务器地址
const headers = ref({ Authorization: "Bearer " + getToken() });
const fileList = ref([]);
const showTip = computed(
  () => props.isShowTip && (props.fileType || props.fileSize)
);
const oFileType = ref('')

watch(() => props.modelValue, val => {
  fileList.value = [];
  if (val) {
    let temp = 1;
    // 首先将值转为数组
    let ids = [];
    if (val instanceof Array) {
      val.map(item => {
        if (item instanceof Object && item && item.id) {
          ids.push(item.id)
        }
        if (item instanceof String && item) {
          ids.push(item)
        }
      })
    }
    if (val instanceof Object && val && val.id) {
      ids.push(val.id)
    }
    if (val instanceof String && val) {
      ids.push(val)
    }
    if (ids.length > 0) {
      doGet(svc, '/attachment/ids', {ids: ids.join(',')}, false).then(res => {
        fileList.value = res.map(item => {
          item.uid = item.uid || new Date().getTime() + temp++;
          return item;
        });
      })
    }
  }
},{ deep: true, immediate: true });

// 上传前校检格式和大小
function handleBeforeUpload(file) {
  // 校检文件类型
  if (props.fileType.length) {
    const fileName = file.name.split('.');
    const fileExt = fileName[fileName.length - 1];
    oFileType.value = fileExt
    const isTypeOk = props.fileType.indexOf(fileExt) >= 0;
    if (!isTypeOk) {
      alertWarningMsg(`文件格式不正确, 请上传 ${props.fileType.join("/")} 格式文件!`)
      return false;
    }
  }
  // 校检文件大小
  if (props.fileSize) {
    const isLt = file.size / 1024 / 1024 <= props.fileSize;
    if (!isLt) {
      alertWarningMsg(`上传文件大小不能超过 ${props.fileSize} MB!`);
      return false;
    }
  }
  proxy.$modal.loading("正在上传文件，请稍候...");
  number.value++;
  return true;
}

function closeBtn() {
  attachmentVisible.value = false
}
// 文件个数超出
function handleExceed() {
  alertWarningMsg(`上传文件数量不能超过 ${props.limit} 个!`);
}

// 上传失败
function handleUploadError(err) {
  console.error(err)
  alertErrorMsg("上传文件失败");
}

// 上传成功回调
function handleUploadSuccess(res, file) {
  console.log('res-----------',res)
  console.log('file-----------',file)
  if (res.code === '000') {
    res.data.file = file
    uploadList.push(res.data);
    uploadedSuccessfully();
    console.log('props.oParentId',props.oParentId)
    emit('uploadedSuccess', res.data, props.oParentId)
  } else {
    number.value--;
    proxy.$modal.closeLoading();
    alertWarningMsg(res.msg);
    proxy.$refs['fileUpload'].handleRemove(file);
    uploadedSuccessfully();
  }
}

function handleDownload(file) {
  doDownload(svc, '/customAttachment/download/' + file.id, {})
}

// 上传结束处理
function uploadedSuccessfully() {
  if (number.value > 0 && uploadList.length === number.value) {
    fileList.value = fileList.value.concat(uploadList)
    uploadList = [];
    number.value = 0;
    // emit("update:modelValue", oFile);
    proxy.$modal.closeLoading();
  }
}

// 对象转成指定字符串分隔
function listToString(list, separator) {
  let strs = "";
  separator = separator || ",";
  for (let i in list) {
    if (list[i].url) {
      strs += list[i].url + separator;
    }
  }
  return strs !== '' ? strs.substring(0, strs.length - 1) : '';
}
</script>

<style lang="scss">
.upload-file {
  display: inline-block;
}
</style>
